<?php
namespace app\common\model;

class Weixin extends BaseModel{
	public $weixin;
	public $scene_id;
	public $user_id;

	function __construct(){
		//导入微信包，并初化
		import('ThinkWechat', EXTEND_PATH, '.class.php');
		$this->weixin = new \ThinkWechat('', true);
		$config = model('Config')->_get('', 'weixin');
		$this->weixin->appid  = $config['appid'];
		$this->weixin->secret = $config['appsecret'];

	}
	/**
	 * 更新微信用户信息
	 * @param  [type] $openid     [description]
	 * @param  [type] $unionid    [description]
	 * @param  string $nickname   [description]
	 * @param  string $sex        [description]
	 * @param  string $province   [description]
	 * @param  string $city       [description]
	 * @param  string $country    [description]
	 * @param  string $headimgurl [description]
	 * @return [type]             [description]
	 */
	public function update_user($openid, $unionid, $nickname = '', $sex = '', $province = '', $city = '', $country = '', $head_imgurl = ''){
		if($this->is_exists_openid($openid) == false){
			$data['openid']      = $openid;
			$data['unionid']     = $unionid ? $unionid : '';
			$data['nickname']    = $nickname ? $nickname : '';
			$data['sex']         = $sex ? $sex : 0;
			$data['province']    = $province ? $province : '';
			$data['city']        = $city ? $city : '';
			$data['country']     = $country ? $country : '';
			$data['headimgurl']  = $head_imgurl ? $head_imgurl : '';
			$data['create_time'] = time();
			db('WeixinUser')->insert($data);
		}else{
			$where['openid'] = $openid;
			if($unionid){$data['unionid']       = $unionid;}
			if($nickname){$data['nickname']     = $nickname;}
			if($sex){$data['sex']               = $sex;}
			if($province){$data['province']     = $province;}
			if($city){$data['city']             = $city;}
			if($country){$data['country']       = $country;}
			if($head_imgurl){$data['headimgurl'] = $head_imgurl;}
			
			if($data){
				$data['is_delete'] = 0;
				$data['edit_time'] = time();
				db('WeixinUser')->where($where)->update($data);
			}
		}
	}
	/**
	 * 取消关注操作
	 * @param  [type] $openid 用户微信账号
	 */
	public function unsubscribe($openid){
		$where['openid'] = $openid;
		$data['is_delete']   = 1;
		$data['delete_time'] = time();
		db('WeixinUser')->where($where)->update($data);
	}
	/**
	 * 判断用户是否存在
	 * @param  [type]  $openid [description]
	 * @return boolean                 [description]
	 */
	public function is_exists_openid($openid){
		$where['openid'] = $openid;
		$count = db('WeixinUser')->where($where)->count();
		return $count > 0;
	}
	/**
	 * 获取扫描ID的用户ID
	 * @param  [type] $scene_id 扫描ID
	 */
	public function get_scene_id_user_id($scene_id){
		$where['scene_id'] = $scene_id;
		$user_id = db('WeixinQrcode')->where($where)->value('user_id');
		return $user_id ? $user_id : 0;
	}
	/**
	 * 生成scene_id
	 * @param  [type] $user_id  用户ID
	 * @param  string $other_id 其它ID
	 * @param  array  $params   参数
	 */
	public function generate_scene_id($user_id = '', $other_id = '', $data_type = 'login', $params = array(), $app_type = 'system'){
		
		$data['user_id']      = $user_id ? $user_id : 0;
		$data['other_id']     = $other_id ? $other_id : 0;
		$data['data_type']    = $data_type ? $data_type : 'login';
		$data['params']       = $params ? json_encode($params) : '';
		$data['weixin_appid'] = $this->weixin->appid ? $this->weixin->appid : '';
		$data['app_type']     = $app_type ? $app_type : 'system';
		$md5 = md5(json_encode($data));
		$scene_id = $this->get_md5_scene_id($md5);
		if(!$scene_id){
			$data['md5'] = $md5;
			$data['create_time'] = time();
			$model = db('WeixinQrcode');
			$model->insert($data);
			$scene_id = $model->getLastInsID();
		}

		return $scene_id;
	}
	/**
	 * 获取二维码URL地址
	 * @param  [type] $user_id  用户ID
	 * @param  string $other_id 其它ID
	 * @param  array  $params   参数
	 */
	public function get_qrcode_url($data_type = 'login', $user_id, $other_id, $params = array(), $app_type = 'system'){
		// 生成扫描ID
		$scene_id = $this->generate_scene_id($user_id, $other_id, $data_type, $params, $app_type);
		$info = db('WeixinQrcode')->where(array('scene_id' => $scene_id))->find();
		$qrcode_url  = $info['url'];
		$is_time_out = (time() - $info['create_time']) > 2592000;
		if($is_time_out || !$qrcode_url){
			//导入微信包，并初化
			$qrcode_url = $this->weixin->get_qrcode_url($scene_id);
			if(!$qrcode_url){
				return false;
			}
			// 更新URL地址
			db('WeixinQrcode')->where(array('scene_id' => $scene_id))->update(array('url' => $qrcode_url));
		}
		$this->scene_id = $scene_id;
		return $qrcode_url;
	}
	/**
	 * 获取扫描信息
	 * @param  [type] $scene_id 场景ID
	 * @param  string $openid   openid
	 * @param  string $unionid  unionid
	 */
	public function get_scan_info($scene_id, $openid = '', $unionid = ''){
		$info = $this->get_scene_id_info($scene_id, true);
		$data_type = $info['data_type'];
		$app_type  = $info['app_type'];
		$app_type  = $app_type ? $app_type : 'system';
		$params    = json_decode($info['params'], true);
		$content   = '';

		// 获取微信用户信息
		$wx_user       = $this->get_openid_userinfo($openid);
		$unionid       = $wx_user['unionid'];
		$nickname      = $wx_user['nickname'];
		$headimgurl    = $wx_user['headimgurl'];
		$sex           = $wx_user['sex'];
		$province_name = $wx_user['province'];
		$city_name     = $wx_user['city'];
		// 未关注的不处理
		if($wx_user && $wx_user['is_delete']){
			return false;
		}
		if(!$wx_user){
			$wx_user       = $this->weixin->get_openid_userinfo($openid);
			$unionid       = $wx_user['unionid'];
			$nickname      = $wx_user['nickname'];
			$headimgurl    = $wx_user['headimgurl'];
			$sex           = $wx_user['sex'];
			$province_name = $wx_user['province'];
			$city_name     = $wx_user['city'];
			$subscribe     = $wx_user['subscribe'];
			// 未关注的不处理
			if(!$subscribe){
				return false;
			}
			$this->update_user(
				$openid,
				$unionid,
				$nickname,
				$wx_user['sex'],
				$wx_user['province'],
				$wx_user['city'],
				$wx_user['country'],
				$headimgurl
			);
		}
		$user_model = model('User');
		switch ($data_type) {
			
			// 扫描登录，自动注册登录
			case 'login':
				// $app_type = $params['app_type'] ? $params['app_type'] : 'web';
				$appid = $params['appid'] ? $params['appid'] : 0;
				$user_model->setParams('head_url', $headimgurl);
				$user_model->setParams('sex', $sex);
				$user_model->setParams('province_name', $province_name);
				$user_model->setParams('city_name', $city_name);
				if($user_info = $user_model->sso_login('weixin', $openid, $nickname, true, $app_type, $appid)){
					$user_id = $user_info['user_id'];
					$this->user_id = $user_id;
					db('WeixinQrcode')->where(array('scene_id' => $scene_id))->update(array('scan_user_id' => $user_id));
					// 获取应用信息
					$app_name = '科目记平台';
					if($appid){
						$app_info = db('AppSet')->where(array('appid' => $appid))->find();
						$app_name = $app_info['title'];
					}
					$content = $nickname . '，您好，您于' . date('Y年m月d日 H:i:s') . '通过微信扫描成功授权登录《' . $app_name . '》，感谢您的使用！';
				}else{
					$content = '登录失败，请稍候再试！';
				}
				
				break;

			// 扫描绑定
			case 'bind':
				$user_id   = $info['user_id'];
				$user_name = $user_model->get_user_name($user_id);
				db('WeixinQrcode')->where(array('scene_id' => $scene_id))->update(array('scan_user_id' => $user_id));
				if($user_model->sso_bind('weixin', $user_id, $openid, $nickname)){
					$content = $nickname . '，您好，您于' . date('Y年m月d日 H:i:s') . '通过微信扫描成功绑定数豆者平台账号(' . $user_name . '，UserID:' . $user_id .')，感谢您的使用！';
				}else{
					$content = $user_model->tips_info;
				}
			default:
				# code...
				break;
		}
		return $content;
	}
	/**
	 * 获取OPENID用户信息
	 * @param  string $openid 用户ID
	 */
	public function get_openid_userinfo($openid = ''){
		$info = db('WeixinUser')->where(array('openid' => $openid))->find();

		return $info ? $info : array();
	}
	/**
	 * 获取MD5的scene_id
	 * @param  string $md5 [description]
	 * @return [type]      [description]
	 */
	public function get_md5_scene_id($md5 = ''){
		$where['md5'] = $md5;
		$scene_id = db('WeixinQrcode')->where($where)->value('scene_id');

		return $scene_id ? $scene_id : '';
	}
	/**
	 * 获取扫描ID信息
	 * @param  string  $scene_id 扫描ID
	 * @param  boolean $is_scan  是否扫描
	 */
	public function get_scene_id_info($scene_id = '', $is_scan = false){
		$where['scene_id'] = $scene_id;
		$info = db('WeixinQrcode')->where($where)->find();
		if($is_scan){
			db('WeixinQrcode')->where($where)->setInc('scan_num');
		}

		return $info ? $info : array();
	}
	public function set_menu($menu){
		foreach ($menu as $rs) {
			$row['type'] = 'view';
			$row['name'] = $rs['title'];
			$row['url']  = $rs['url'];
			if($rs['parent_id'] > 0){
				$list[$rs['parent_id']][] = $row;
			}
		}
		foreach ($menu as $rs) {
			$row['type'] = 'view';
			$row['name'] = $rs['title'];
			$row['url']  = $rs['url'];
			if($rs['parent_id'] == 0){
				$level_menu = $list[$rs['menu_id']];
				if(!empty($level_menu)){
					$row['sub_button'] = $level_menu;
				}
				$new_menu[] = $row;
				unset($row['sub_button']);
			}
		}
		$button    = array('button' => $new_menu);
		$json_menu = json_encode($button, JSON_UNESCAPED_UNICODE);
		$data = $this->weixin->set_menu($json_menu);
		$this->tips_info = $this->weixin->tips_info;
		return $data;
	}
}